/* 
 * MIT License
 *
 * Copyright (c) 2019 极简美 @ konishi5202@163.com
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include "mt_timer.h"

TIMER_DECLEAR(test);
int count = 0;
int timer1, timer2;
void timeout_handle1(void *arg)
{
    printf("[%ld]:timeout1..\n", time(NULL));
}

void timeout_handle2(void *arg)
{
    printf("[%ld]:timeout2\n", time(NULL));
	count++;
	if(count > 2)
	{
		TIMER_DEL(test, timer1);
	}
}

TIMER_CREATE(test); // 创建实例

// 设置定时时间
int setTimeout(struct itimerspec *tv, int sec, int nsec)
{
	tv->it_value.tv_sec = sec;
	tv->it_value.tv_nsec = nsec;
	tv->it_interval = tv->it_value;
}

int main(void)
{
	struct itimerspec tv[10];

    TIMER_INIT(test, 10); // 最大10个
    
	setTimeout(&tv[0], 2, 0);
	setTimeout(&tv[1], 0, 800*1000*1000);
    timer1 = TIMER_ADD(test, &tv[0], 8, timeout_handle1, NULL, NULL);
    printf("[%ld]:timer_add : %d\n", time(NULL), TIMER_COUNT(test));
    timer2 = TIMER_ADD(test, &tv[1], 3, timeout_handle2, NULL, NULL);
    printf("[%ld]:timer_add : %d\n", time(NULL), TIMER_COUNT(test));

	printf("timer1: %d, timer2: %d\n", timer1, timer2);
    printf("[%ld]:timer_add : %d\n", time(NULL), TIMER_COUNT(test));
    
    getchar();
    TIMER_DEL(test, timer1);
    printf("[%ld]:timer_del : %d\n", time(NULL), TIMER_COUNT(test));
    TIMER_CLEAR(test);
    printf("[%ld]:timer_clear : %d\n", time(NULL), TIMER_COUNT(test));

    TIMER_DEINIT(test);
    
    return 0;
}

